<template>
  <div :class="['login', $ua.isFromPc() ? 'z-web' : 'z-phone']">
    <el-dialog
      v-if="$ua.isFromPc()"
      :before-close="close"
      :visible.sync="loginDialog"
      width="50%"
      center
      :modal="false"
      :lock-scroll="true"
      class="login-dialog"
    >
      <div slot="title" class="title">欢迎来到艺览天下之海淀</div>
      <el-tabs v-model="activeName" stretch>
        <el-tab-pane label="密码登陆" name="passwordForm" class="pass">
          <el-form
            :model="passwordForm"
            :rules="passwordRules"
            ref="passwordForm"
          >
            <el-form-item prop="user_name">
              <el-input
                v-model="passwordForm.user_name"
                placeholder="手机号/邮箱"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password" class="password">
              <el-input
                v-model="passwordForm.password"
                @keyup.enter.native="submit(activeName)"
                placeholder="密码"
                show-password
              ></el-input>
            </el-form-item>
            <div class="loginFoot">
              <span class="forget" @click="handleForgetPassword">忘记密码</span>
              <span>|</span>
              <span class="register" @click="handleRegister"> 注册 </span>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="短信登陆" name="shortMessageForm" class="short">
          <el-form
            :model="shortMessageForm"
            :rules="shortRules"
            ref="shortMessageForm"
          >
            <el-form-item prop="cellphone">
              <el-input
                v-model="shortMessageForm.cellphone"
                placeholder="手机号"
              ></el-input>
            </el-form-item>
            <el-form-item prop="code" class="password">
              <el-input
                v-model="shortMessageForm.code"
                @keyup.enter.native="submit(activeName)"
                placeholder="验证码"
              ></el-input>
              <span
                @click="inputCode"
                :class="['shortCode', wait ? 'timeCode' : '']"
                >{{ codeMessage }}</span
              >
            </el-form-item>
            <div class="loginFoot">
              <span class="forget">忘记密码</span>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit(activeName)">确 定</el-button>
      </div>
      <!-- <div class="other">
        <span class="line"></span>
        <span class="text">其他登陆方式</span>
      </div>
      <div class="weChat">
        <img src="@/static/img/login/icon_wechat.png" alt="">
      </div> -->
      <div class="agreement">
        登陆或注册即代表同意
        <span class="user" @click="goAgreement">用户协议</span>
        和
        <span class="policy" @click="goPolicy">隐私政策</span>
      </div>
    </el-dialog>
    <div v-else class="my-phone">
      <div class="header">
        <client-only>
          <van-icon class="back" name="arrow-left" color="#fff" @click="back" />
        </client-only>
        登陆艺览天下之海淀
      </div>
      <div class="login-title">
        <div
          @click="active = 0"
          :class="['short-message', active === 0 ? 'active' : '']"
        >
          短信登陆
        </div>
        <div
          @click="active = 1"
          :class="['password', active === 1 ? 'active' : '']"
        >
          密码登陆
        </div>
      </div>
      <div class="login-content">
        <div v-show="active === 1" class="short-form">
          <el-form
            :model="passwordForm"
            :rules="passwordRules"
            ref="passwordForm"
          >
            <el-form-item prop="user_name">
              <el-input
                v-model="passwordForm.user_name"
                placeholder="手机号/邮箱"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password" class="password">
              <el-input
                v-model="passwordForm.password"
                @keyup.enter.native="submit('passwordForm')"
                placeholder="密码"
                show-password
              ></el-input>
            </el-form-item>
            <div class="loginFoot">
              <span class="forget" @click="handleForgetPassword">忘记密码</span>
              <span>|</span>
              <span class="register" @click="handleRegister"> 注册 </span>
            </div>
            <van-checkbox v-model="checked" shape="square"></van-checkbox>
            <div class="agreement">
              登陆或注册即代表同意
              <span class="user" @click="goAgreement">用户协议</span>
              和
              <span class="policy" @click="goPolicy">隐私政策</span>
            </div>
            <div class="dialog-footer">
              <div class="all-center" @click="submit('passwordForm')">
                登 陆
              </div>
            </div>
          </el-form>
        </div>
        <div v-show="active === 0">
          <el-form
            :model="shortMessageForm"
            :rules="shortRules"
            ref="shortMessageForm"
          >
            <el-form-item prop="cellphone">
              <el-input
                v-model="shortMessageForm.cellphone"
                placeholder="手机号"
              ></el-input>
            </el-form-item>
            <el-form-item prop="code" class="password">
              <el-input
                v-model="shortMessageForm.code"
                @keyup.enter.native="submit('shortMessageForm')"
                placeholder="验证码"
              ></el-input>
              <span
                @click="inputCode"
                :class="['shortCode', wait ? 'timeCode' : '']"
                >{{ codeMessage }}</span
              >
            </el-form-item>
            <van-checkbox v-model="checked" shape="square"></van-checkbox>
            <div class="agreement">
              登陆或注册即代表同意
              <span class="user" @click="goAgreement">用户协议</span>
              和
              <span class="policy" @click="goPolicy">隐私政策</span>
            </div>
            <div class="dialog-footer">
              <div class="all-center" @click="submit('shortMessageForm')">
                登 陆/注 册
              </div>
            </div>
            <div class="loginFoot">
              <span class="forget">忘记密码</span>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserPhoto } from "../../utils/downloadFile";
export default {
  data() {
    const validatePassword = (rule, value, callback) => {
      const reg_tel =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/; // 手机号正则
      const reg_email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; // 邮箱正则
      console.log(this.activeName);
      if (!value) {
        return callback(new Error("手机号/邮箱不能为空"));
      } else {
        callback();
      }
      // if (!reg_tel.test(value) && !reg_email.test(value)) {
      //   callback(new Error('您输入的手机号/邮箱格式不正确'))
      // } else {
      //   callback()
      // }
    };
    const validateShort = (rule, value, callback) => {
      const reg_tel =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/; // 手机号正则
      if (!value) {
        return callback(new Error("手机号不能为空"));
      }
      if (!reg_tel.test(value)) {
        callback(new Error("您输入的手机号格式不正确"));
      } else {
        callback();
      }
    };
    return {
      active: 0,
      checked: false,
      passwordForm: {
        user_name: "",
        password: "",
      },
      shortMessageForm: {
        cellphone: "",
        code: "",
      },
      activeName: "passwordForm",
      passwordRules: {
        user_name: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      shortRules: {
        cellphone: [
          { required: true, trigger: "blur", validator: validateShort },
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { max: 6, min: 6, message: "验证码长度为6", trigger: "blur" },
        ],
      },
      codeMessage: "获取短信验证码",
      wait: false,
      timer: null,
    };
  },
  computed: {
    loginDialog() {
      return this.$store.state.user.loginDialog;
    },
  },
  mounted() {},
  methods: {
    getUserPhoto,
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params;
          if (formName == "passwordForm") {
            params = {
              ...this.passwordForm,
              password: this.$md5(
                this.passwordForm.user_name +
                  "_" +
                  this.$md5(this.passwordForm.password)
              ),
            };
          } else {
            params = {
              ...this.shortMessageForm,
            };
          }
          if (!this.checked && !this.$ua.isFromPc())
            return this.$message.error("请先同意用户协议");
          this.$api
            .login(
              { ...params },
              formName == "passwordForm" ? {} : { op: "login_by_cellphone" }
            )
            .then((res) => {
              if (res.status == "$SUCCESS") {
                // debugger
                this.$store.commit("user/SET_TOKEN", res.result.ak);
                this.$store.commit("user/SET_INFO", res.result);
                this.$cookies.set("info", res.result, {
                  maxAge: 60 * 60 * 24 * 3,
                });
                this.$store.commit(
                  "user/SET_HEADIMG",
                  res.result.user_info.photo
                );
                console.log(
                  "this.$store.state",
                  this.getUserPhoto(
                    "user",
                    res.result?.user_info?.art_info.data_id,
                    "photo"
                  )
                );
                this.close();
                this.$router.push("/home");
              } else {
                this.$message.error(res.message);
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    close() {
      this.$refs.passwordForm.resetFields();
      this.$refs.shortMessageForm.resetFields();
      // 登陆窗口统一由vuex控制
      this.$store.commit("user/SET_LOGIN", false);
    },
    // 获取短信验证码
    inputCode() {
      this.$refs["shortMessageForm"].validateField("cellphone", (valid) => {
        if (!valid) {
          this.getLoginCode();
          let time = 60;
          this.wait = true;
          this.timer = this.codeMessage = time + "s后重新发送";
          setInterval(() => {
            time--;
            this.codeMessage = time + "s后重新发送";
            if (time <= 0) {
              this.codeMessage = "获取验证码";
              clearInterval(this.timer);
            }
          }, 1000);
        }
      });
    },
    // 获取短信验证码
    getLoginCode() {
      const params = {
        op: "send_login_ver_code",
        reciever: this.shortMessageForm.cellphone,
      };
      this.$api.getLoginCode({ ...params }).then((res) => {
        if (res.status == "$SUCCESS") {
          this.$message.success("获取短信验证码");
        }
      });
    },
    // 跳转到注册页面
    handleRegister() {
      this.$router.push({ path: "/register" });
      // 注册页是不在菜单上的，防止菜单高亮，清空已存储的路由
      // this.$store.commit('router/setActiveRoute', { activeRouter: '' })
      this.close();
      // this.customScrollTop()
    },
    // 跳转到忘记密码页面
    handleForgetPassword() {
      this.$router.push({ path: "/forgetPassword" });
      this.close();
    },
    // 跳转到协议页
    goAgreement() {
      this.$router.push({ path: "/policy/agreement" });
      // 注册页是不在菜单上的，防止菜单高亮，清空已存储的路由
      this.$store.commit("router/setActiveRoute", { activeRouter: "" });
      this.close();
    },
    // 跳转到隐私页
    goPolicy() {
      this.$router.push({ path: "/policy/policy" });
      // 注册页是不在菜单上的，防止菜单高亮，清空已存储的路由
      this.$store.commit("router/setActiveRoute", { activeRouter: "" });
      this.close();
    },
    // 移动端返回事件
    back() {
      this.$router.go(-1);
    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

<style lang="less" scoped>
.login {
  &.z-web {
    ::v-deep(.el-tabs__nav-scroll) {
      width: 50% !important;
      margin: 0 auto !important;
    }

    ::v-deep(.el-tabs__nav-wrap::after) {
      background: transparent;
    }

    ::v-deep(.el-tabs__item.is-active) {
      color: #000;
    }

    ::v-deep(.el-tabs__active-bar) {
      background-color: #cab094;
    }

    ::v-deep(.el-tabs__item:hover) {
      color: #000;
    }

    ::v-deep(.el-input__inner) {
      border: 0;
      border-bottom: 1px solid #ccc;
      padding: 0;
    }

    ::v-deep(input::-webkit-input-placeholder) {
      color: #666;
      font-size: 16px;
      opacity: 0.6;
      font-family: Source Han Serif SC;
    }

    ::v-deep(.el-dialog--center .el-dialog__body) {
      padding: 30px 100px 14px;
      font-size: 18px;
    }

    ::v-deep(.el-dialog__footer) {
      padding: 10px 100px 20px;
    }

    ::v-deep(.el-button--primary) {
      width: 100%;
      height: 60px;
      background-color: #dfcbb6;
      border: 0;
      border-radius: 0;
      margin-bottom: 30px;
      font-size: 24px;
    }

    ::v-deep(.password) {
      margin-bottom: 14px;
      position: relative;

      .shortCode {
        position: absolute;
        right: 0;
        cursor: pointer;
        color: #dfcbb6;
        background-color: #fff;

        &.timeCode {
          color: #999;
          pointer-events: none;
        }
      }
    }
    ::v-deep(.el-tabs__item) {
      height: 40px;
      line-height: 40px;
      font-size: 18px;
    }
    ::v-deep(.el-form-item) {
      margin-bottom: 22px;
    }
    ::v-deep(.el-form-item__content) {
      font-size: 14px;
    }
    ::v-deep(.el-input__inner) {
      height: 40px;
      line-height: 40px;
    }
    ::v-deep(.el-form-item__error) {
      line-height: 1;
      font-size: 14px;
    }

    .title {
      font-size: 30px;
      font-weight: 600;
      font-family: 楷体;
      // letter-spacing: 3px;
      color: #cab094;
    }

    .loginFoot {
      text-align: right;
      margin-bottom: 25px;

      .forget {
        cursor: pointer;
      }

      .register {
        cursor: pointer;
      }
    }

    .other {
      position: relative;
      .line {
        display: inline-block;
        height: 1px;
        width: 100%;
        background-color: #ccc;
      }

      .text {
        width: 120px;
        font-size: 14px;
        color: #666;
        margin: 0 4px;
        position: absolute;
        left: 50%;
        margin-left: -60px;
        top: 7px;
        text-align: center;
        background: #fff;
      }
    }

    .weChat {
      text-align: center;
      margin: 14px 0 32px;
      cursor: pointer;
      color: #666;
      font-size: 14px;
    }

    .agreement {
      text-align: center;

      .user,
      .policy {
        color: #000;
        cursor: pointer;
      }
    }
  }

  &.z-phone {
    .header {
      width: 100%;
      height: pxtorem(88);
      background: #000;
      position: fixed;
      top: 0;
      z-index: 1001;
      padding: 0 pxtorem(30);
      display: flex;
      align-items: center;
      font-size: pxtorem(30);
      font-weight: 800;
      color: #dfcbb6;
      justify-content: center;
    }

    .login-title {
      text-align: center;
      margin-bottom: pxtorem(100);

      .short-message,
      .password {
        display: inline-block;
        font-size: pxtorem(28);
        color: #333;
      }

      .short-message {
        margin-right: pxtorem(80);
      }

      .active {
        position: relative;
        color: #000;
        font-weight: bold;

        &::after {
          content: "";
          position: absolute;
          bottom: pxtorem(-10);
          left: 0;
          z-index: 1;
          width: pxtorem(115);
          height: pxtorem(3);
          background-color: #cab094;
          border-radius: 3px;
        }
      }
    }

    .login-content {
      padding: 0 pxtorem(85) pxtorem(190);

      .agreement {
        display: inline-block;
        margin-bottom: pxtorem(40);
      }

      ::v-deep(.van-checkbox) {
        margin-bottom: pxtorem(40);
        display: inline-block;
        vertical-align: bottom;
      }

      .password {
        margin-bottom: pxtorem(20);
        // ::v-deep(.el-form-item) {
        //   margin-bottom: pxtorem(10);
        // }
      }
    }

    .password {
      position: relative;
    }

    .shortCode {
      position: absolute;
      right: pxtorem(23);
      font-size: 28px;
      color: #cab094;
    }

    .dialog-footer {
      width: 100%;
      height: pxtorem(72);
      div {
        width: 100%;
        height: 100%;
        background: #dfcbb6;
        font-size: pxtorem(30);
        font-weight: 800;
        color: #fff;
      }
    }

    .back {
      position: absolute;
      left: pxtorem(30);
    }
  }
}
</style>
